package com.thundersoft.musicplayer.utils;

import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;

import com.thundersoft.musicplayer.pojo.Music;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liuzh0705
 * @Date:2021/07/27/下午6:30
 * @Description:
 */
public class MusicUtils {

    /**
     * 扫描系统里的音频文件
     * @return  music 的 list 集合
     */
    public static List<Music> getMusicList(Context context) {
        List<Music> list = new ArrayList<>();
        // 媒体库查询语句
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.AudioColumns.IS_MUSIC);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                Music music = new Music();
                // 获取歌曲的信息
                music.setMusicName(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
                music.setMusicSinger(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
                music.setMusicPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
                music.setMusicTime(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
                music.setMusicSize(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE)));
                if (music.getMusicSize() > 1000 * 800) {
                    // 将歌名和歌手分割开
                    if (music.getMusicName().contains("-")) {
                        String[] str = music.getMusicName().split("-");
                        music.setMusicSinger(str[0]);
                        music.setMusicName(str[1]);
                    }
                    list.add(music);
                }
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 格式化歌曲时长
     * @param time
     * @return
     */
    public static String formatTime(int time) {
        if (time / 1000 % 60 <10) {
            return time / 1000 / 60 + ":0" + time / 1000 % 60;
        } else {
            return time / 1000 / 60 + ":" + time / 1000 % 60;
        }
    }

}
